package com.calwen.xsmarthome.exception;

import com.calwen.xsmarthome.util.ResultUtil;
import com.calwen.xsmarthome.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.BadRequestException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 全局异常处理类
 *
 * @author calwen
 * @since 2025/2/17
 */
@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public ResultVO<String> failException(Exception e) {
        log.error("[操作失败] ：===> {}", e.getMessage(), e);
        return ResultUtil.error(e.getMessage());
    }

    @ExceptionHandler({BadRequestException.class, MissingServletRequestParameterException.class})
    public ResultVO<String> badRequestException(Exception e) {
        log.error("[坏的请求] ：===> {}", e.getMessage(), e);
        return ResultUtil.badRequest(e.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResultVO<String> validException(MethodArgumentNotValidException e) {
        log.error("[请求常数检验] ：===> {}", e.getMessage(), e);
        String message = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining());
        return ResultUtil.badRequest(message);
    }

    @ExceptionHandler({RuntimeException.class, Exception.class, Throwable.class})
    public ResultVO<String> runtimeException(Exception e) {
        log.error("[发生异常]：===> {}", e.getMessage(), e);
        return ResultUtil.exception(e.getMessage());
    }


}
